<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebAssembly Delaunay 三角剖分测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            text-align: center;
        }
        canvas {
            border: 1px solid #ccc;
            margin-top: 20px;
        }
        .controls {
            margin: 20px 0;
        }
        button {
            padding: 8px 16px;
            margin: 0 10px;
            cursor: pointer;
        }
        input[type="number"] {
            width: 60px;
            padding: 8px;
        }
    </style>
</head>
<body>
    <h1>WebAssembly Delaunay 三角剖分测试</h1>
    
    <div class="controls">
        <label for="pointCount">点数: </label>
        <input type="number" id="pointCount" min="3" max="1000" value="50">
        <button id="generatePoints">生成随机点</button>
        <button id="runTriangulation">执行三角剖分</button>
        <button id="clearCanvas">清空画布</button>
        <div style="margin-top: 10px;">
            <label for="triangulationType">三角剖分类型: </label>
            <select id="triangulationType">
                <option value="wasm">WebAssembly版本</option>
                <option value="js">JavaScript版本</option>
            </select>
        </div>
    </div>
    
    <canvas id="canvas" width="800" height="600"></canvas>
    
    <div id="status">状态: 等待加载WebAssembly模块...</div>
    <div style="margin-top: 20px;">
        <a href="timing_stats.html" target="_blank">查看三角剖分计时统计</a>
    </div>
    
    <!-- 先加载delaunay.js库，它会暴露全局变量Delaunay -->
    <script src="./libs/delaunay.js"></script>
    <script type="module">
        // 导入DelaunayWasm实例
        import delaunay from './test_wasm_delaunay.mjs';
        
        // 获取DOM元素
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const generateBtn = document.getElementById('generatePoints');
        const triangulateBtn = document.getElementById('runTriangulation');
        const clearBtn = document.getElementById('clearCanvas');
        const pointCountInput = document.getElementById('pointCount');
        const statusDiv = document.getElementById('status');
        
        // 点集和三角形数据
        let points = [];
        let triangles = [];
        let triangulationPoints = []; // 存储用于三角剖分的点数组
        
        // 初始化
        async function init() {
            // 加载WebAssembly模块
            const loaded = await delaunay.loadWasm();
            if (loaded) {
                statusDiv.textContent = '状态: WebAssembly模块已加载完成，可以开始测试';
                triangulateBtn.disabled = false;
            } else {
                statusDiv.textContent = '状态: WebAssembly模块加载失败，请检查文件是否存在';
                triangulateBtn.disabled = true;
            }
        }
        
        // 生成随机点
        function generateRandomPoints(count) {
            points = [];
            for (let i = 0; i < count; i++) {
                // 在画布内生成随机点，边距20px
                const x = 20 + Math.random() * (canvas.width - 40);
                const y = 20 + Math.random() * (canvas.height - 40);
                points.push({ x, y });
            }
            drawPoints();
        }
        
        // 绘制点
        function drawPoints() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制点
            ctx.fillStyle = 'blue';
            points.forEach(point => {
                ctx.beginPath();
                ctx.arc(point.x, point.y, 3, 0, Math.PI * 2);
                ctx.fill();
            });
        }
        
        // 绘制三角形
        function drawTriangles() {
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 首先绘制所有原始点（蓝色）
            ctx.fillStyle = 'blue';
            points.forEach(point => {
                ctx.beginPath();
                ctx.arc(point.x, point.y, 3, 0, Math.PI * 2);
                ctx.fill();
            });
            
            // 然后绘制筛选后的点（绿色）
            if (triangulationPoints.length > 0) {
                ctx.fillStyle = 'green';
                triangulationPoints.forEach(point => {
                    ctx.beginPath();
                    ctx.arc(point.x, point.y, 4, 0, Math.PI * 2);
                    ctx.fill();
                });
            }
            
            // 绘制三角形
            ctx.strokeStyle = 'red';
            ctx.lineWidth = 1;
            
            // 每3个点组成一个三角形
            for (let i = 0; i < triangles.length; i += 3) {
                // 使用用于三角剖分的点数组
                const p1 = triangulationPoints[triangles[i]];
                const p2 = triangulationPoints[triangles[i + 1]];
                const p3 = triangulationPoints[triangles[i + 2]];
                
                if (p1 && p2 && p3) {
                    ctx.beginPath();
                    ctx.moveTo(p1.x, p1.y);
                    ctx.lineTo(p2.x, p2.y);
                    ctx.lineTo(p3.x, p3.y);
                    ctx.closePath();
                    ctx.stroke();
                }
            }
        }
        
        // 执行三角剖分
        async function runTriangulation() {
            if (points.length < 3) {
                alert('请至少生成3个点');
                return;
            }

            const useWasm = triangulationTypeSelect.value === 'wasm';
            statusDiv.textContent = `状态: 正在执行${useWasm ? 'WebAssembly' : 'JavaScript'}版本的三角剖分...`;

            try {
                const startTime = performance.now();
                
                // 添加center和radius参数
                const center = [0.1, 0.1]; // 中心点坐标
                const radius = 2; // 半径
                
                let filteredPoints = points;
                let filterTime = 0; // 筛选耗时
                // 对于JavaScript版本，应用点筛选
                if (!useWasm) {
                    const filterStartTime = performance.now(); // 开始筛选计时
                    
                    // 将相对坐标转换为画布实际坐标
                    const canvasCenter = {
                        x: center[0] * canvas.width,
                        y: center[1] * canvas.height
                    };
                    const canvasRadius = radius * 100; // 放大半径以便于观察
                    
                    // 筛选出距离中心点在半径范围内的点
                    filteredPoints = points.filter(point => {
                        const dx = point.x - canvasCenter.x;
                        const dy = point.y - canvasCenter.y;
                        return Math.sqrt(dx * dx + dy * dy) <= canvasRadius;
                    });
                    
                    filterTime = performance.now() - filterStartTime; // 计算筛选耗时
                    
                    if (filteredPoints.length < 3) {
                        statusDiv.textContent = '状态: 筛选后点数量不足3个，无法进行三角剖分';
                        return;
                    }
                }
                
                triangles = await delaunay.triangulate(filteredPoints);
                // 存储用于三角剖分的点数组
                triangulationPoints = filteredPoints;
                const endTime = performance.now();
                const totalTime = endTime - startTime;

                if (triangles) {
                    const pointCount = filteredPoints.length;
                    const triangulationTime = totalTime - filterTime;
                    
                    if (useWasm) {
                        statusDiv.textContent = `状态: WebAssembly版本三角剖分完成，耗时: ${totalTime.toFixed(2)}ms，使用了 ${pointCount} 个点，生成了 ${triangles.length / 3} 个三角形`;
                    } else {
                        statusDiv.textContent = `状态: JavaScript版本三角剖分完成，总耗时: ${totalTime.toFixed(2)}ms (筛选: ${filterTime.toFixed(2)}ms, 三角剖分: ${triangulationTime.toFixed(2)}ms)，使用了 ${pointCount} 个点，生成了 ${triangles.length / 3} 个三角形`;
                    }
                    drawTriangles();
                } else {
                    statusDiv.textContent = `状态: ${useWasm ? 'WebAssembly' : 'JavaScript'}版本三角剖分失败`;
                }
            } catch (error) {
                console.error('三角剖分错误:', error);
                statusDiv.textContent = `状态: ${useWasm ? 'WebAssembly' : 'JavaScript'}版本三角剖分过程中发生错误`;
            }
        }
        
        // 清空画布
        function clearCanvas() {
            points = [];
            triangles = [];
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            statusDiv.textContent = '状态: 画布已清空';
        }
        
        // 获取三角剖分类型选择器
        const triangulationTypeSelect = document.getElementById('triangulationType');

        // 绑定事件监听
        generateBtn.addEventListener('click', () => {
            const count = parseInt(pointCountInput.value) || 50;
            generateRandomPoints(count);
        });
        
        triangulateBtn.addEventListener('click', runTriangulation);
        
        clearBtn.addEventListener('click', clearCanvas);

        // 切换三角剖分类型
        triangulationTypeSelect.addEventListener('change', () => {
            const useWasm = triangulationTypeSelect.value === 'wasm';
            delaunay.setUseWasm(useWasm);
            statusDiv.textContent = `状态: 已切换到${useWasm ? 'WebAssembly' : 'JavaScript'}版本的三角剖分`;
        });
        
        // 初始化
        init();
    </script>
</body>
</html>